//
//  GameViewController.m
//  FIght Game
//
//  Created by iD Student on 7/1/13.
//  Copyright (c) 2013 iD Student. All rights reserved.
//

#import "GameViewController.h"
#import "DifficultyViewController.h"

@interface GameViewController ()

@end

@implementation GameViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    appsettings = [NSUserDefaults standardUserDefaults];
    highScore = [NSUserDefaults standardUserDefaults];
    //   playing = YES;
    x = 0;
    int difficulty = [appsettings integerForKey:@"difficulty"];
    if(difficulty == 1){
        x = 1;
    }
    else if(difficulty == 2){
        x = .5;
    }
    else if(difficulty == 3){
        x = 0.25;
    }
    else {
        x = 0.15;
    }
    playing = YES;
    timer = [NSTimer scheduledTimerWithTimeInterval:x target:self selector:@selector(create) userInfo:nil repeats:YES];
    score = 0;
    enemies = [[NSMutableArray alloc] init];
    increase = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(diffUp) userInfo:nil repeats:YES];
    scoreLabel.text = [[NSString alloc] initWithFormat:@"Score: %d", score];
    toOp = 0;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)create
{
    if(playing == YES){
        Enemy *theEnemy = [[Enemy alloc] init];
        [enemies addObject:theEnemy];
        [self.view addSubview:[theEnemy spawn]];
        [self.view bringSubviewToFront:scoreLabel];
        int numberAlive = 0;
        Enemy *enemy;
        for(int q = 0; q<[enemies count]; q++){
            enemy = [enemies objectAtIndex:q];
            if([enemy isAlive]){
                numberAlive ++;
            }
        }
        if(numberAlive > 20){
            [self gameOver];
        }
    }
    
}
- (void) touchesBegan:(NSSet *) touches withEvent: (UIEvent *) event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:[self view]];\
    
    Enemy *enemy;
    
    for(int i=0; i<[enemies count]; i++){
        enemy = [enemies objectAtIndex:i];
        
        if(CGRectContainsPoint(enemy.imageView.frame, touchPoint))
        {
            score += [enemy getPoints];
            [enemy kill];
            scoreLabel.text = [[NSString alloc] initWithFormat:@"Score: %d", score];
        }
    }
    
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [timer invalidate];
    [increase invalidate];
    playing = NO;
    enemies = nil;
}

-(void)gameOver
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"GAME OVER" message:[[NSString alloc] initWithFormat:@"You've been defeated! Your score was %d",score] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: @"Play Again", @"Options", nil];
    [alert show];
    playing = NO;
    
    //Add top 5 items from NSUserDefaults
    //Add 6th item as last inserted
    //Sort
    //Save top 5
   
    
    NSArray *j = [[NSArray alloc] initWithObjects:[highScore objectForKey:@"HS_1"],[highScore integerForKey:@"HS_2"],[highScore integerForKey:@"HS_3"],[highScore integerForKey:@"HS_4"],[highScore integerForKey:@"HS_5"],[[NSString alloc] initWithFormat:@"%d",score], nil];
    
    if(score > [highScore integerForKey:@"HS_1"])
    {
        someRandomArray = [[NSArray alloc] initWithObjects:[[NSString alloc] initWithFormat:@"%d",score],[highScore integerForKey:@"HS_1"],[highScore integerForKey:@"HS_2"],[highScore integerForKey:@"HS_3"],[highScore integerForKey:@"HS_4"], nil];
    }
    else if(score > [highScore integerForKey:@"HS_2"] && score < [highScore integerForKey:@"HS_1"])
    {
        someRandomArray = [[NSArray alloc] initWithObjects:[highScore objectForKey:@"HS_1"],[[NSString alloc] initWithFormat:@"%d",score],[highScore integerForKey:@"HS_2"],[highScore integerForKey:@"HS_3"],[highScore integerForKey:@"HS_4"], nil];
    }
    else if(score > [highScore integerForKey:@"HS_3"] && score < [highScore integerForKey:@"HS_2"])
    {
        someRandomArray = [[NSArray alloc] initWithObjects:[highScore objectForKey:@"HS_1"],[highScore integerForKey:@"HS_2"],[[NSString alloc] initWithFormat:@"%d",score],[highScore integerForKey:@"HS_3"],[highScore integerForKey:@"HS_4"], nil];
    }
    else if(score > [highScore integerForKey:@"HS_4"] && score < [highScore integerForKey:@"HS_3"])
    {
       someRandomArray = [[NSArray alloc] initWithObjects:[highScore objectForKey:@"HS_1"],[highScore integerForKey:@"HS_2"],[highScore integerForKey:@"HS_3"],[[NSString alloc] initWithFormat:@"%d",score],[highScore integerForKey:@"HS_4"], nil];
    }
    else if(score > [highScore integerForKey:@"HS_5"] && score < [highScore integerForKey:@"HS_4"])
    {
        someRandomArray = [[NSArray alloc] initWithObjects:[highScore objectForKey:@"HS_1"],[highScore integerForKey:@"HS_2"],[highScore integerForKey:@"HS_3"],[highScore integerForKey:@"HS_4"],[[NSString alloc] initWithFormat:@"%d",score],nil];
    }
    
    [highScore setObject:someRandomArray forKey:@"HighScores"];
    [highScore synchronize];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        x = 0;
        int difficulty = [appsettings integerForKey:@"difficulty"];
        if(difficulty == 1){
            x = 1;
        }
        else if(difficulty == 2){
            x = .5;
        }
        else if(difficulty == 3){
            x = 0.25;
        }
        else {
            x = 0.15;
        }
        score = 0;
        Enemy *enemy;
        for(int i = 0; i<[enemies count]; i++)
        {
            enemy = [enemies objectAtIndex:i];
            [enemy kill];
        }
        // increase = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(diffUp) userInfo:nil repeats:YES];
        scoreLabel.text = [[NSString alloc] initWithFormat:@"Score: %d", score];
        [self performSelector:@selector(newGame) withObject:nil afterDelay:1.5];
    }
    if(buttonIndex == 2)
    {
        toOp = 1;
        [self performSegueWithIdentifier:@"toOptions" sender:self];
    }
    
}
-(void) newGame
{
    playing = YES;
}

-(void) diffUp
{
    if(playing == 1)
    {
        x = x/1.1;
        [timer invalidate];
        timer = [NSTimer scheduledTimerWithTimeInterval:x target:self selector:@selector(create) userInfo:nil repeats:YES];
    }
    
}
- (void)viewWillAppear:(BOOL)animated
{
    if(toOp == true)
    {
    [super viewWillAppear:animated];
    [self.navigationController popViewControllerAnimated:YES];
    
    }
}
@end
